<?php
/*
This sends a little bit of JSON to say if the user is logged in. 
*/

require_once( 'core.php' );
require_once( 'current_user_api.php' );
require_once( 'bugnote_api.php' );


//gets the metadata requiremnts / settings based on the field path key
function get_field_settings($metadataSettings, $fKPath){
	
	$datasetMetadata = $metadataSettings["fields"];
	$fieldSettings = false;
	$numKeys = count($fKPath);
	
	//echo "Number keys!! ".$numKeys ;
	//echo print_r($datasetMetadata);
	
	if($numKeys == 4){
		$fieldSettings = $datasetMetadata[$fKPath[0]]["subfields"][$fKPath[1]]["subfields"][$fKPath[2]]["subfields"][$fKPath[3]];
	}
	elseif($numKeys == 3){
		$fieldSettings = $datasetMetadata[$fKPath[0]]["subfields"][$fKPath[1]]["subfields"][$fKPath[2]];
	}
	elseif($numKeys == 2){
		$fieldSettings = $datasetMetadata[$fKPath[0]]["subfields"][$fKPath[1]];
	}
	elseif($numKeys == 1){
		$fieldSettings = $datasetMetadata[$fKPath[0]];
	}

	return $fieldSettings;
}

//used on this page, to add user supplied field description to the right level of the hierarchy of table meta
function update_field_multiVal_description($newDesData, $fieldKeysPath, $creator, $fieldName, $fieldVal, $valIndex){
	
	$numKeys = count($fieldKeysPath);
	if($numKeys == 4){
		if(!isset($newDesData[$fieldKeysPath[0]]["subfields"][$fieldKeysPath[1]]["subfields"][$fieldKeysPath[2]]["subfields"][$fieldKeysPath[3]])){
			$actDesFieldArray = array("name" => $fieldName, "values" => false);
			$newDesData[$fieldKeysPath[0]]["subfields"][$fieldKeysPath[1]]["subfields"][$fieldKeysPath[2]]["subfields"][$fieldKeysPath[3]] = $actDesFieldArray;
		}
		else{
			$actDesFieldArray = $newDesData[$fieldKeysPath[0]]["subfields"][$fieldKeysPath[1]]["subfields"][$fieldKeysPath[2]]["subfields"][$fieldKeysPath[3]];
		}
		$newDesData[$fieldKeysPath[0]]["subfields"][$fieldKeysPath[1]]["subfields"][$fieldKeysPath[2]]["subfields"][$fieldKeysPath[3]] = multiUpdate($actDesFieldArray, $creator, $fieldName, $fieldVal, $valIndex);
	}
	elseif($numKeys == 3){
		if(!isset($newDesData[$fieldKeysPath[0]]["subfields"][$fieldKeysPath[1]]["subfields"][$fieldKeysPath[2]])){
			$actDesFieldArray = array("name" => $fieldName, "values" => false);
			$newDesData[$fieldKeysPath[0]]["subfields"][$fieldKeysPath[1]]["subfields"][$fieldKeysPath[2]] = $actDesFieldArray;
		}
		else{
			$actDesFieldArray = $newDesData[$fieldKeysPath[0]]["subfields"][$fieldKeysPath[1]]["subfields"][$fieldKeysPath[2]];
		}
		$newDesData[$fieldKeysPath[0]]["subfields"][$fieldKeysPath[1]]["subfields"][$fieldKeysPath[2]] = multiUpdate($actDesFieldArray, $creator, $fieldName, $fieldVal, $valIndex);
	}
	elseif($numKeys == 2){
		if(!isset($newDesData[$fieldKeysPath[0]]["subfields"][$fieldKeysPath[1]])){
			$actDesFieldArray = array("name" => $fieldName, "values" => false);
			$newDesData[$fieldKeysPath[0]]["subfields"][$fieldKeysPath[1]] = $actDesFieldArray;
		}
		else{
			$actDesFieldArray = $newDesData[$fieldKeysPath[0]]["subfields"][$fieldKeysPath[1]];
		}
		$newDesData[$fieldKeysPath[0]]["subfields"][$fieldKeysPath[1]] = multiUpdate($actDesFieldArray, $creator, $fieldName, $fieldVal, $valIndex);
	}
	elseif($numKeys == 1){
		if(!isset($newDesData[$fieldKeysPath[0]])){
			$actDesFieldArray = array("name" => $fieldName, "values" => false);
			$newDesData[$fieldKeysPath[0]] = $actDesFieldArray;
		}
		else{
			$actDesFieldArray = $newDesData[$fieldKeysPath[0]];
		}
		$newDesData[$fieldKeysPath[0]] = multiUpdate($actDesFieldArray, $creator, $fieldName, $fieldVal, $valIndex);
	}
	
	return $newDesData;
}


function multiUpdate($actDesFieldArray, $creator, $fieldName, $fieldVal, $valIndex){
	
	if(!$fieldVal){
		if(is_array($actDesFieldArray["values"])){
			$actDesFieldArray["values"][$valIndex] = false;
		}
		else{
			$actDesFieldArray["values"] = false;
		}
	}
	else{
		//first check to see if the value already exists
		if(!is_array($actDesFieldArray["values"])){
			$actDesFieldArray["values"] = array();
		}
		
		$valueExists = false;
		if(count($actDesFieldArray["values"])>0){
			foreach($actDesFieldArray["values"] as $valArray){
				if(is_array($valArray)){
					if($valArray["text"] == $newDesVal){
						$valueExists = true;
					}
				}
			}
		}
		
		if(!$valueExists){
			$actDesFieldArray["values"][$valIndex] = array("text" => $fieldVal, "noteCreator" => $creator); 
		}
		
	}
	
	return $actDesFieldArray;
}



auth_ensure_user_authenticated( );
//helper_begin_long_process( );


# extracts the user information for the currently logged in user
# and prefixes it with u_
$f_user_id = gpc_get_int( 'id', auth_get_current_user_id() );
$row = user_get_row( $f_user_id );

extract( $row, EXTR_PREFIX_ALL, 'u' );
$u_email = user_get_email( $u_id );
$u_realname = user_get_realname( $u_id );




$t_plugin_path = config_get( 'plugin_path' );
require_once( $t_plugin_path . 'DataRefine' . DIRECTORY_SEPARATOR . 'TableMetadata.php' );
require_once( $t_plugin_path . 'DataRefine' . DIRECTORY_SEPARATOR . 'JSONstore.php' );
require_once( $t_plugin_path . 'DataRefine' . DIRECTORY_SEPARATOR . 'MetadataStandards.php' );

$refineURI = plugin_config_get( 'refineLocalURI' );
if(!$refineURI){
	$refineURI = plugin_config_get( 'refineBaseURI' );
}


$projectID = $_POST["grProject"]; 
$fieldKey = $_POST["fieldKey"];
$fieldVal = $_POST["value"];
$valIndex = $_POST["valIndex"];

if(strlen($fieldVal)<1){
	$fieldVal = false;
}


$tableMetaObj = new TableMetadata;
$tableMetaObj->refineURI = $refineURI;
$tableMetaObj->currentUser = $f_user_id;
$tableMetaObj->GRprojectID = $projectID;
$tableMetaObj->get_metadata();
$tableMetaObj->add_User_Role($f_user_id, $u_username, "meta");

$tableMetadata = $tableMetaObj->currentMetadata;

//prep the descritptive metadata!
$newDesData = $tableMetadata["description"];


//get metadata settings and requirements
$datasetMetadata = $tableMetaObj->get_descriptive_fields();


//now we needed to do some work to get settings for the field being updated
//the settings are in an array, and the fieldKey passed by the user has path information
//for a field that may be nested in parent fields.
if(!stristr($fieldKey, "-")){
	$fieldKeyArray = array(0 => $fieldKey);
}
else{
	$fieldKeyArray = explode("-", $fieldKey);
}

$i = 0;
$fieldKeyCount = count($fieldKeyArray);
$fieldKeysPath = array();
//this loop makes all the field keys needed to reference a specific metadata descriptive field
while($i < $fieldKeyCount){
	
	if($i == 0){
		$actKey = $fieldKeyArray[$i];
	}
	else{
		$actKey = $actKey."-".$fieldKeyArray[$i];
	}

	$fieldKeysPath[] = $actKey;
$i++;	
}//end loop


$fieldSetting = get_field_settings($datasetMetadata, $fieldKeysPath);

$fieldName = $fieldSetting["name"];

if(!$fieldSetting["multipleOK"]){
	$valIndex = 0;
}

$newDesData = update_field_multiVal_description($newDesData, $fieldKeysPath, $u_username, $fieldName, $fieldVal, $valIndex);
$tableMetadata["description"] = $newDesData;
$tableMetaObj->currentMetadata = $tableMetadata;
$tableMetaObj->count_description_done();



$json = json_encode($tableMetadata, 1);
$JSONstore = new JSONstore;
$JSONstore->setDirectory("metadata");
$JSONstore->save_json($projectID, $json);

$JSONout = array("fieldKey" => $fieldKey,
			    "valIndex" => $valIndex,
			    "name" => $fieldName,
			    "type" => $fieldSetting["type"],
			    "required" => $fieldSetting["required"],
			    "reqCompleted" => $tableMetaObj->descriptionsDone,
			    "subfields" => $fieldSetting["subfields"],
			    "success" => true);


$output = json_encode($JSONout, 1);


$bugNote = ucwords($fieldName)." provided (descriptive metadata)";




	require_once( 'bug_api.php' );
	require_once( 'bugnote_api.php' );

	$f_bug_id		= $tableMetadata["issueIDs"]["describeIssue"];
	$f_private		= false;
	$f_time_tracking	= null;
	$f_bugnote_text	= trim($bugNote);
	$t_bugnote_id = bugnote_add( $f_bug_id, $bugNote, $f_time_tracking, $f_private, BUGNOTE );



//now output for AJAX call from the Refine Login Screen
if(!isset($_GET["callback"])){
	header('Content-Type: application/json; charset=utf8');
	echo $output;
}
else{
	header('Content-Type: application/json; charset=utf8');
	$callback = $_GET["callback"];
	echo $callback."(".$output.");";
}


?>
